﻿using Microsoft.Extensions.Caching.Memory;

namespace Magic.Core;
/// <summary>
/// 缓存服务
/// </summary>
[Injection]
public class MemoryCacheService : IMemberCacheService
{
    private readonly IMemoryCache _memoryCache;
    public MemoryCacheService(IMemoryCache memoryCache)
    {
        _memoryCache = memoryCache;
    }
    /// <summary>
    /// 判断缓存是否存在
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public async Task<bool> ExistKey(string key)
    {
        var cacheResult = _memoryCache.TryGetValue(key, out var result);
        if (cacheResult)
        {
            return true;
        }
        return false;
    }
    /// <summary>
    /// 获取缓存
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="key"></param>
    /// <returns></returns>
    public async Task<T> Get<T>(string key)
    {
        return _memoryCache.Get<T>(key);
    }
    /// <summary>
    /// 获取缓存
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public async Task<dynamic> Get(string key)
    {
        return _memoryCache.Get<dynamic>(key);
    }
    /// <summary>
    /// 移除缓存
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public async Task Remove(string key)
    {
        _memoryCache.Remove(key);
    }
    /// <summary>
    /// 设置缓存
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public async Task Set(string key, object value)
    {
        _memoryCache.Set(key, value);
    }
    /// <summary>
    /// 增加缓存并设置过期时间
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <param name="expire"></param>
    /// <returns></returns>
    public async Task Set(string key, object value, TimeSpan expire)
    {
        var cacheEntryOptions = new MemoryCacheEntryOptions()
            .SetAbsoluteExpiration(expire);
        _memoryCache.Set(key, value, cacheEntryOptions);
    }
}
